﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LizzabethBrownRealEstate.Models;
using System.Globalization;
using System.Security.Permissions;
using System.Web.Security;
using System.Net.Mail;
using System.Collections.Specialized;
using System.Configuration;

namespace LizzabethBrownRealEstate.Controllers
{
    public class AdminController : Controller
    {
        LBRDataContext dc = new LBRDataContext();

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult AdminOptions()
        {
            return View();
        }

        #region Property Functions
        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult PropertyList()
        {
            return View();
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult NewProperty()
        {
            return View(new RealEstateProperty());
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult EditProperty(int propertyId)
        {
            ViewData.Add("PropertyId", propertyId);
            return View();
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult SaveOrUpdateProperty(int propertyId)
        {
            RealEstateProperty rep;
            if (propertyId > 0)
                rep = dc.GetRealEstateProperty(propertyId);
            else
                rep = new RealEstateProperty();

            string err = "";
            try
            {
                /*
                rep.Basement = (Request.Form["Bsmnt"] == null) ? false : true;
                rep.NewConstruction = (Request.Form["NewConst"] == null) ? false : true;
                rep.Feature = (Request.Form["Ftur"] == null) ? false : true;
                rep.Historic = (Request.Form["Hist"] == null) ? false : true; ;
                rep.GarageAttached = (Request.Form["GargAttch"] == null) ? false : true; ;
                rep.Garage = (Request.Form["Garg"] == null) ? false : true; ;               
                */
                if (propertyId == 0)
                {
                    dc.RealEstateProperties.InsertOnSubmit((RealEstateProperty)rep);
                }
                TryUpdateModel(rep, Request.Form.AllKeys);
                if (Request.Form["Location"] != null)
                {
                    rep.Location = dc.GetLocation(int.Parse(Request.Form["Location"].ToString()));
                }
                dc.SubmitChanges();
            }
            //catch (System.Web.Mvc.PopulateTypeException ex)
            //{
            //    err = ex.LoadExceptions[0].ToString();
            //}
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            propertyId = rep.PropertyId;
            ViewData.Add("PropertyId", propertyId);
            return RedirectToAction("EditProperty", new {propertyId = propertyId });
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult DeleteProperty(int propertyId)
        {
            RealEstateProperty rep = dc.GetRealEstateProperty(propertyId);
            if (rep != null)
            {
                rep.Deleted = true;
                dc.SubmitChanges();
            }
            return RedirectToAction("PropertyList");
        }

        #endregion

        #region User Functions

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult EditUser(string userId)
        {
            ViewData.Add("UserId", userId);
            return View();
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult UserList()
        {
            return View();
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult SaveOrUpdateUser(string id)
        {
            if (String.IsNullOrEmpty(Request.Form["UserName"]))
            {
                return RedirectToAction("AdminOptions");
            }

            User u;
            if (id != null)
                u = dc.GetUser(id);
            else
                u = new User();

            TryUpdateModel(u, Request.Form.AllKeys);
            u.IsAdmin = (Request.Form["Admin"] == null) ? false : true;
            u.HasAgent = (Request.Form["Agent"] == null) ? false : true;
            if (id == null)
                dc.Users.InsertOnSubmit(u);

            MembershipUser mu = Membership.GetUser(u.UserId);
            if (u.IsAdmin)
            {
                if (mu != null)
                {
                    string[] users = { mu.UserName };
                    Roles.AddUsersToRole(users, "Administrator");
                }
            }
            else
            {
                if (mu != null)
                {
                    if (Roles.IsUserInRole(mu.UserName, "Administrator"))
                    {
                        Roles.RemoveUserFromRole(mu.UserName, "Administrator");
                    }
                }
            }

            dc.SubmitChanges();
            return RedirectToAction("EditUser", u);
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult DeleteUser(string id)
        {
            User u;
            if (id != null)
                u = dc.GetUser(id);
            else
                u = new User();

            u.Deleted = true;
            dc.SubmitChanges();

            Membership.DeleteUser(u.UserName, true);
            return RedirectToAction("UserList");
        }

        #endregion

        #region Mail
        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult SendEmail()
        {
            return View();
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult SendMail()
        {
            NameValueCollection section = (NameValueCollection)ConfigurationManager.GetSection("emailInfo");
            string body = "";
            if (Request.Form["Body"] != null)
            {
                body = Request.Form["Body"].ToString();
            }

            string subject = "";
            if (Request.Form["Subject"] != null)
            {
                 subject = Request.Form["Subject"].ToString();
            }

            string user = "";
            if (Request.Form["User"] != null)
            {
                user = Request.Form["User"].ToString();
            }

            User u = dc.GetUser(user);

            MailAddress to = new MailAddress(u.Email);
            MailMessage message = new MailMessage();
            message.To.Add(to);
            message.IsBodyHtml = true;
            message.Subject = subject;
            message.Body = body;
            SmtpClient smtp = new SmtpClient();

            smtp.Send(message);

            return RedirectToAction("SendEmail");
        }

        #endregion

        #region Photos
        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult AddPhoto(int propertyId)
        {
            ViewData.Add("PropertyId", propertyId);
            return RedirectToAction("NewPhoto");
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public void DeletePhotoAndEdit(int photoId, int propertyId)
        {
            Photo p = dc.GetPhoto(photoId);
            if (p != null)
            {
                p.Deleted = true;
                dc.SubmitChanges();

                AddPhoto(propertyId);
            }

        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult SavePhoto(int propertyId)
        {
            RealEstateProperty rep;
            rep = dc.GetRealEstateProperty(propertyId);
            if (Request.Files.Count >= 0)
            {
                foreach( string f in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[f] as HttpPostedFileBase;
                    if (file.ContentLength == 0)
                    {
                        continue;
                    }
                    else
                    {
                        Photo newPhoto = new Photo();

                        newPhoto.PropertyId = rep.PropertyId;
                        newPhoto.FileName = System.IO.Path.GetFileName(file.FileName);
                        dc.Photos.InsertOnSubmit(newPhoto);
                        dc.SubmitChanges();

                        string path = Request.MapPath("../Repository/") + newPhoto.FileName;
                        file.SaveAs(path);
                    }
                }
            }
            ViewData.Add("PropertyId", propertyId);
            return RedirectToAction("NewPhoto");
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult DeletePhoto(int photoId, int propertyId)
        {
            Photo p = dc.GetPhoto(photoId);
            if (p != null)
            {
                p.Deleted = true;
                dc.SubmitChanges();

                ViewData.Add("PropertyId", propertyId);
                
            }
            return RedirectToAction("EditProperty");
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult SetFeaturedPhoto(int photoId, int propertyId)
        {
            RealEstateProperty r = dc.GetRealEstateProperty(propertyId);
            foreach (Photo p in r.Photos)
            {
                if (p.PhotoId == photoId)
                    p.Featured = true;
                else
                    p.Featured = false;
            }
            dc.SubmitChanges();

            ViewData.Add("PropertyId", propertyId);
            return RedirectToAction("EditProperty");

        }

        #endregion

        #region Resources
        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult NewResource()
        {
            return RedirectToAction("EditResource", new Resource());
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult EditResource(int resourceId)
        {
            ViewData.Add("ResourceId", resourceId);
            return View();
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult ResourceList()
        {
            return View();
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult DeleteResource(int id)
        {
            dc.GetResource(id).Deleted = true;
            dc.SubmitChanges();
            return RedirectToAction("ResourceList");
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult SaveOrUpdateResource(int id)
        {
            Resource res = new Resource();

            if (!String.IsNullOrEmpty(Request.Form["Url"]))
            {
                if (id > 0)
                    res = dc.GetResource(id);
                else
                    dc.Resources.InsertOnSubmit(res);

                TryUpdateModel(res, Request.Form.AllKeys);

                dc.SubmitChanges();
            }
            return RedirectToAction("ResourceList", res);
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public void SetResourceOrder(int resourceId, int dispOrder)
        {
            Resource res = dc.Resources.Where(r => r.ResourceId == resourceId).SingleOrDefault();
            if (res != null)
            {
                res.DisplayOrder = dispOrder;
                dc.SubmitChanges();
            }
        }

        #endregion

        #region Events
        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult EventList()
        {
            return View();
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult NewEvent()
        {
            Event e = new Event();
            e.EventStart = DateTime.Now;
            e.EventEnd = DateTime.Now;
            return RedirectToAction("EditEvent", e);
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult EditEvent(int eventId)
        {
            ViewData.Add("EventId", eventId);
            return View();
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult DeleteEvent(int id)
        {
            dc.GetEvent(id).Deleted = true;
            dc.SubmitChanges();
            return RedirectToAction("EventList");
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult SaveOrUpdateEvent(int id)
        {

            Event evt;
            if (id > 0)
                evt = dc.GetEvent(id);
            else
                evt = new Event();

            TryUpdateModel(evt, Request.Form.AllKeys);

            string sStart = Request.Form["EventStartDate"] + " " + Request.Form["EventStartTime"];
            string sEnd = Request.Form["EventStartDate"] + " " + Request.Form["EventEndTime"];
            DateTime st = new DateTime();
            DateTime.TryParse(sStart, out st);
            DateTime end = new DateTime();
            DateTime.TryParse(sEnd, out end);
            evt.EventStart = new Nullable<DateTime>(st);
            evt.EventEnd = new Nullable<DateTime>(end);
            if (id == 0)
                dc.Events.InsertOnSubmit(evt);

            dc.SubmitChanges();
            return RedirectToAction("EditEvent", new { eventId = evt.EventId });
        }

        #endregion

        #region Documents

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult DocumentList()
        {
            return View();
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult NewDocument()
        {
            ViewData.Add("DocumentId", 0);
            return RedirectToAction("EditDocument", new { documentId = 0 });
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult EditDocument(int documentId)
        {
            ViewData.Add("DocumentId", documentId);
            return View();
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult DeleteDocument(int documentId)
        {
            Document d = dc.GetDocument(documentId);
            if (d != null)
            {
                d.Deleted = true;
                dc.SubmitChanges();

                ViewData.Add("DocumentId", documentId);                
            }
            return RedirectToAction("DocumentList");
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult SaveOrUpdateDocument(int documentId)
        {
            Document doc;
            if (documentId > 0)
                doc = dc.GetDocument(documentId);
            else
            {
                doc = new Document();

                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase file = Request.Files[0] as HttpPostedFileBase;
                    if (file.ContentLength > 0)
                    {
                        doc.FileName = System.IO.Path.GetFileName(file.FileName);

                        string path = Request.MapPath("../Repository/") + doc.FileName;
                        file.SaveAs(path);
                    }
                }
            }

            TryUpdateModel(doc, Request.Form.AllKeys);
            if (documentId == 0)
                dc.Documents.InsertOnSubmit(doc);

            if (!String.IsNullOrEmpty(doc.Title) && !String.IsNullOrEmpty(doc.FileName))
            {
                dc.SubmitChanges();
            }
            ViewData.Add("DocumentId", documentId);
            return RedirectToAction("DocumentList");
             
        }

        #endregion

        #region NewsItems

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult NewsItemList() 
        {
            return View();
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult NewNewsItem()
        {
            NewsItem n = new NewsItem();
            n.Title = "New Item";
            n.Body = "";
            return RedirectToAction("EditNewsItem", n);
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult EditNewsItem(int newsItemId)
        {
            ViewData.Add("NewsItemId", newsItemId);
            return View();
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult DeleteNewsItem(int newsItemId)
        {
            dc.GetNewsItem(newsItemId).Deleted = true;
            dc.SubmitChanges();
            return RedirectToAction("NewsItemList");
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult SaveOrUpdateNewsItem(int newsItemId)
        {

            NewsItem n;
            if (newsItemId > 0)
                n = dc.GetNewsItem(newsItemId);
            else
                n = new NewsItem();

            TryUpdateModel(n, Request.Form.AllKeys);
            if (Request.Form["Featured"] == null)
                n.Featured = false;

            if (newsItemId == 0)
                dc.NewsItems.InsertOnSubmit(n);

            dc.SubmitChanges();
            return RedirectToAction("EditNewsItem", new { newsItemId = n.NewsItemId });
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
        public ActionResult SetFeaturedNewsItem(int newsItemId, bool featured)
        {
            NewsItem n = dc.GetNewsItem(newsItemId);
            n.Featured = featured;
            dc.SubmitChanges();
            return RedirectToAction("NewsItemList");
        }

        #endregion
    }
}
